package pl.easyshop.core.services.security;

import java.util.ArrayList;
import java.util.Collection;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import pl.easyshop.core.model.UserModel;
import pl.easyshop.core.services.security.enums.UserRole;

/**
 * Implementation of component which loads the user specific data. The major
 * task of this component is to assign a correct user roles set based on
 * authorized user properties.
 * 
 * @author pwitkowski
 */
@Service("userSecurityService")
public class UserSecurityServiceImpl implements UserDetailsService {

	/** Log. */
	private final static Logger LOG = Logger.getLogger(UserSecurityServiceImpl.class);

	/** Implementation of {@link UserDAO}. */
	@Autowired
	private Object hbUserDAO;

	@Transactional(readOnly = true)
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
		UserModel userModel = null;//hbUserDAO.findByLogin(username);
		if (LOG.isDebugEnabled()) {
			LOG.debug("User loaded for name [" + username + "]: " + userModel);
		}
		if (userModel == null) {
			throw new UsernameNotFoundException("User with name " + username
					+ " not found.");
		}
		if (!userModel.isEnabled()) {
			throw new DisabledException("Konto nieaktywne");
		}
		AuthorizedUser authorizedUser = new AuthorizedUser(userModel.getUsername(),
				userModel.getPassword(), userModel.isEnabled(), true, true,
				true, grantRoles(userModel));
		
		authorizedUser.setUserId(userModel.getId());
		return authorizedUser;
	}

	/**
	 * Prepares set of roles based on logged user properties.
	 * 
	 * @param applicationUser
	 * @return
	 */
	private Collection<GrantedAuthority> grantRoles(UserModel userModel) {
		ArrayList<GrantedAuthority> roles = new ArrayList<GrantedAuthority>();
		
		/*if (UserRole.ROLE_ADMIN.equals(userModel.getRole())) {
			roles.add(UserRole.ROLE_ADMIN);
		} else if (UserRole.ROLE_BASIC.equals(userModel.getRole())) {
				roles.add(UserRole.ROLE_BASIC);
		}*/
		if (LOG.isDebugEnabled()) {
			LOG.debug("Roles granted for user: " + roles);
		}
		return roles;
	}

}
